package com.kotlin.book.activity

import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Rect
import android.icu.text.SimpleDateFormat
import android.icu.util.Calendar
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.SeekBar
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.graphics.Insets
import androidx.core.view.GravityCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.book.R
import com.kotlin.book.adapter.ReadCommentItemAdapter
import com.kotlin.book.adapter.ReadDirectoryItemAdapter
import com.kotlin.book.adapter.ReadTextItemAdapter
import com.kotlin.book.api.BookApi
import com.kotlin.book.api.ChapterApi
import com.kotlin.book.api.CommentApi
import com.kotlin.book.databinding.ActivityReadBinding
import com.kotlin.book.entry.Chapter
import com.kotlin.book.entry.Comment
import com.kotlin.book.util.Util
import java.util.Locale
import kotlin.math.floor


class ReadActivity : AppCompatActivity() {
    private lateinit var binding: ActivityReadBinding
    private var directoryList: List<Chapter> = listOf()
    private var chapterList: MutableList<Chapter> = mutableListOf()
    private var isNight: Boolean = false
    private var bookId: Int = 0
    private var showInput: Boolean = false

    //已加载章节下标
    private var index = 0

    //目录下标
    private var directoryIndex = 0
    private var showHeaderNav = false

    //private lateinit var countDownTimer: CountDownTimer
    private var onePage = 1
    private val pageSize = 10
    private var pageList: MutableList<Int> = mutableListOf()
    private lateinit var systemBars: Insets
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityReadBinding.inflate(layoutInflater)
        setContentView(binding.root)
        //根据系统ui设置边距
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            binding.frameLayout.setPadding(
                systemBars.left,
                systemBars.top,
                systemBars.right,
                systemBars.bottom
            )
            binding.directoryPopup.setPadding(
                systemBars.left,
                systemBars.top,
                systemBars.right,
                systemBars.bottom
            )
            insets
        }
        // 参数接收
        val bundle = this.intent.extras
        bookId = bundle?.getInt("bookId")!!
        binding.black.setOnClickListener {
            finish()
        }
        initData()
        getBookDetail()
        getChapterDirectory()
        binding.chapterBox.setOnTouchListener(object : View.OnTouchListener {
            var isDragging = false

            override fun onTouch(v: View, event: MotionEvent): Boolean {
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        isDragging = false
                    }

                    MotionEvent.ACTION_MOVE -> {
                        isDragging = true
                    }

                    MotionEvent.ACTION_UP -> {
                        if (!isDragging) {
                            // 如果未拖动，视为单击
                            v.performClick() // 触发单击事件
                        }
                    }
                }
                return false
            }
        })

        // 显示隐藏头部和底部栏目
        binding.chapterBox.setOnClickListener {
            showHeaderNav = !showHeaderNav
            var headerNavTranslationY = 0f
            var footerSelectTranslationY = 0f
            binding.seekBar.progress = directoryIndex
            if (!showHeaderNav) {
                headerNavTranslationY = Util.dpToPx(-60, this).toFloat()
                footerSelectTranslationY = Util.dpToPx(100, this).toFloat()
            } else {
//                if (::countDownTimer.isInitialized) {
//                    countDownTimer.cancel()
//                }
//                countDownTimer = object : CountDownTimer(3000, 1000) {
//                    override fun onTick(p0: Long) {}
//
//                    override fun onFinish() {
//                        if (showHeaderNav) {
//                            binding.chapterBox.performClick()
//                        }
//                    }
//                }
//                countDownTimer.start()
            }
            ObjectAnimator.ofFloat(binding.headerNav, "translationY", headerNavTranslationY).apply {
                duration = 200
                start()
            }
            ObjectAnimator.ofFloat(binding.footerSelect, "translationY", footerSelectTranslationY)
                .apply {
                    duration = 200
                    start()
                }
        }
        //监听输入法
        binding.root.viewTreeObserver.addOnGlobalLayoutListener {
            if (showHeaderNav) {
                val rect = Rect()
                binding.root.getWindowVisibleDisplayFrame(rect) // 获取可见区域
                val screenHeight = binding.root.rootView.height
                val keypadHeight = screenHeight - rect.bottom // 输入法高度
                var translationY = 0f
                showInput = false
                if (keypadHeight > screenHeight * 0.15) {
                    showInput = true
                    // 输入法弹出，获取输入法高度
                    translationY = 0f - keypadHeight + systemBars.bottom
                }
                ObjectAnimator.ofFloat(binding.editBox, "translationY", translationY)
                    .apply {
                        duration = 200
                        start()
                    }
            }
        }
        //显示评论
        binding.setComment.setOnClickListener {
            binding.originalTips.text =
                "原文：" + chapterList[index].content?.replace("\u3000", "")?.replace("\n", "")
            getCommentList(1, 10)
            getCommentCount()
            //评论滚动到底部监听
            binding.commentBox.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    // 获取布局管理器
                    val layoutManager = recyclerView.layoutManager as? LinearLayoutManager
                        ?: return
                    // 检查是否滚动到最后一个可见项
                    val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
                    val totalItemCount = layoutManager.itemCount
                    if (lastVisibleItemPosition == totalItemCount - 1 && dy > 0) {
                        val page = (binding.commentBox.adapter as ReadCommentItemAdapter).page
                        if (page != 0) {
                            getCommentList(page, 10)
                        }
                    }
                }
            })
            binding.mask.visibility = View.VISIBLE
            ObjectAnimator.ofFloat(binding.commentPopup, "translationY", 0f)
                .apply {
                    duration = 200
                    start()
                }
        }
        //提交评论
        binding.sumbit.setOnClickListener {
            val content = binding.editText.text.toString()
            CommentApi.addComment(
                mapOf(
                    "bookId" to bookId,
                    "chapterIndex" to index,
                    "content" to content
                )
            ) { response ->
                if (response?.code == 1) {
                    runOnUiThread {
                        (binding.commentBox.adapter as ReadCommentItemAdapter).addComment(
                            Comment(
                                id = 0,
                                pid = null,
                                userId = 0,
                                replyUserId = null,
                                content = content,
                                bookId = bookId,
                                chapterIndex = index,
                                createTime = Util.getFormatterTime(),
                                updateTime = Util.getFormatterTime(),
                                replyCount = 0,
                                praiseCount = 0,
                                status = 1,
                                isPraise = false,
                                userAvatar = "https://avatars.githubusercontent.com/u/44761321",
                                userNickname = "迷茫。",
                                replyUserAvatar = null,
                                replyUserNickname = null,
                            )
                        )
                        binding.editText.text.clear()
                        binding.commentBox.smoothScrollToPosition(0)
                        binding.mask.performClick()
                    }
                }
            }
        }
        //点击蒙版
        binding.mask.setOnClickListener {
            if (showInput) {
                //关闭软键盘，取消焦点
                val inputMethodManager =
                    getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputMethodManager.hideSoftInputFromWindow(window.decorView.windowToken, 0)
                binding.editText.clearFocus()
                return@setOnClickListener
            }
            binding.mask.visibility = View.GONE
            binding.commentBox.adapter = null
            ObjectAnimator.ofFloat(
                binding.commentPopup,
                "translationY",
                Util.dpToPx(450, this).toFloat()
            )
                .apply {
                    duration = 200
                    start()
                }
        }
        //显示目录
        binding.setDirectory.setOnClickListener {
            (binding.directoryBox.adapter as ReadDirectoryItemAdapter).notifyDataSetChanged()
            binding.readDrawer.openDrawer(GravityCompat.START)
        }
        //排序
        binding.setSort.setOnClickListener {
            (binding.directoryBox.adapter as ReadDirectoryItemAdapter).setSort()
        }
        //切换夜间
        binding.nightBox.setOnClickListener {
            isNight = !isNight
            if (isNight) {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
            } else {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
            }
        }

        //上一章
        binding.prev.setOnClickListener {
            var position = directoryIndex
            val isSort = (binding.directoryBox.adapter as ReadDirectoryItemAdapter).isSort
            if (isSort) {
                position = directoryList.size - 1 - directoryIndex
            }
            if (position != 0) {
                clickDirectory(position - 1)
            }
        }
        //下一章
        binding.next.setOnClickListener {
            var position = directoryIndex
            val isSort = (binding.directoryBox.adapter as ReadDirectoryItemAdapter).isSort
            if (isSort) {
                position = directoryList.size - 1 - directoryIndex
            }
            if (position + 1 != directoryList.size) {
                clickDirectory(position + 1)
            }
        }

        //滑动拉杆
        binding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            var value = 0

            // 当拖动条的进度发生变化时调用
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // progress 是当前的进度值
                value = progress
            }

            // 当用户开始拖动滑块时调用
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            // 当用户停止拖动滑块时调用
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                clickDirectory(value)
            }
        })
    }

    private fun initData() {
        pageList.clear()
        chapterList.clear()
        onePage = floor((directoryIndex / pageSize).toDouble()).toInt() + 1
        index = directoryIndex % pageSize
        getOneChapterList()
    }

    //获取书籍详情
    private fun getBookDetail() {
        BookApi.getBookDetail(mapOf("id" to bookId)) { response ->
            response?.data?.let {
                runOnUiThread {
                    binding.topBookName.text = it.name
                    binding.directoryBookName.text = it.name
                    binding.directoryBookState.text = it.state
                    val calendar = Calendar.getInstance()
                    val formatter = SimpleDateFormat("HH:mm", Locale.getDefault())
                    val formatter1 = SimpleDateFormat("a", Locale.getDefault())
                    val time = formatter1.format(calendar.time) + formatter.format(calendar.time)
                    binding.topTime.text = time
                }
            }
        }
    }

    //获取章节评论
    private fun getCommentList(page: Int, pageSize: Int = 10) {
        binding.commentBox.layoutManager = LinearLayoutManager(this)
        CommentApi.getCommentList(
            mapOf(
                "bookId" to bookId,
                "chapterIndex" to index,
                "page" to page,
                "pageSize" to pageSize
            )
        ) { response ->
            response?.data?.let {
                runOnUiThread {
                    if (binding.commentBox.adapter == null) {
                        binding.commentBox.adapter = ReadCommentItemAdapter(it)
                    } else {
                        (binding.commentBox.adapter as ReadCommentItemAdapter).pushData(it)
                    }
                    if (it.size != pageSize) {
                        (binding.commentBox.adapter as ReadCommentItemAdapter).page = 0
                    }
                }
            }
        }
    }

    //获取章节总数
    private fun getCommentCount() {
        binding.commentBox.layoutManager = LinearLayoutManager(this)
        CommentApi.getCommentCount(
            mapOf(
                "bookId" to bookId,
                "chapterIndex" to index
            )
        ) { response ->
            response?.data?.let {
                runOnUiThread {
                    binding.commentCount.text = "(${it})"
                }
            }
        }
    }

    //获取章节目录
    private fun getChapterDirectory() {
        ChapterApi.getChapterDirectory(mapOf("bookId" to bookId)) { response ->
            response?.data?.let {
                runOnUiThread {
                    directoryList = it
                    binding.seekBar.max = directoryList.size - 1
                    binding.directoryBox.layoutManager = LinearLayoutManager(this)
                    binding.directoryBox.adapter =
                        ReadDirectoryItemAdapter(directoryList, directoryIndex) { position ->
                            run {
                                clickDirectory(position)
                            }
                        }
                    setBottomText()
                }
            }
        }
    }

    //点击章节目录
    private fun clickDirectory(position: Int) {
        directoryIndex = position
        (binding.directoryBox.adapter as ReadDirectoryItemAdapter).setIndex(
            directoryIndex
        )
        binding.seekBar.progress = directoryIndex
        val page = floor((directoryIndex / pageSize).toDouble()).toInt() + 1
        val pageIndex = pageList.indexOf(page)
        if (pageIndex == -1) {
            initData()
        } else {
            index = pageIndex * pageSize + directoryIndex % pageSize
            (binding.chapterBox.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
                index,
                Util.dpToPx(0, this)
            )
        }
        //取消弹出层
        binding.readDrawer.closeDrawer(GravityCompat.START)
        setBottomText()
    }

    private fun setBottomText() {
        binding.bottomChapterName.text = directoryList[directoryIndex].name
        binding.bottomThan.text =
            (directoryIndex + 1).toString() + "/" + directoryList.size.toString()
        val percentage = ((directoryIndex + 1).toFloat() / directoryList.size) * 100
        binding.bottomPercentage.text = String.format("%.2f", percentage) + "%"
    }

    //获取章节列表
    private fun getOneChapterList() {
        binding.chapterBox.layoutManager = LinearLayoutManager(this)
        ChapterApi.getChapterList(
            mapOf(
                "bookId" to bookId,
                "pageSize" to pageSize,
                "page" to onePage
            )
        ) { response ->
            response?.data?.let {
                runOnUiThread {
                    pageList.add(onePage)
                    chapterList.addAll(it)
                    binding.chapterBox.adapter = ReadTextItemAdapter(chapterList) { position ->
                        run {
                            index = position
                            val pageIndex = floor((index / pageSize).toDouble()).toInt()
                            directoryIndex = (pageList[pageIndex] - 1) * pageSize + index % pageSize
                            (binding.directoryBox.adapter as ReadDirectoryItemAdapter).setIndex(
                                directoryIndex
                            )
                            setBottomText()
                            //没加载完
                            if (chapterList.size != directoryList.size) {
                                getChapterList(index)
                            }
                        }
                    }
                    if (index != 0) {
                        (binding.chapterBox.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
                            index,
                            Util.dpToPx(0, this)
                        )
                    }
                }
            }
        }
    }

    //获取章节列表
    private fun getChapterList(index: Int) {
        val position = index + 1
        //向后加载
        if (chapterList.size - position < pageSize) {
            val page = pageList[pageList.size - 1] + 1
            pageList.add(page)
            ChapterApi.getChapterList(
                mapOf(
                    "bookId" to bookId,
                    "pageSize" to pageSize,
                    "page" to page
                )
            ) { response ->
                response?.data?.let {
                    runOnUiThread {
                        if (it.isNotEmpty()) {
                            chapterList.addAll(it)
                            (binding.chapterBox.adapter as ReadTextItemAdapter).setData(chapterList)
                            (binding.chapterBox.adapter as ReadTextItemAdapter).notifyItemRangeInserted(
                                chapterList.size - 1,
                                pageSize
                            )
                        }
                    }
                }
            }
        }
        //向前加载
        if (position < pageSize && pageList[0] != 1) {
            val page = pageList[0] - 1
            pageList.add(0, page)
            ChapterApi.getChapterList(
                mapOf(
                    "bookId" to bookId,
                    "pageSize" to pageSize,
                    "page" to page
                )
            ) { response ->
                response?.data?.let {
                    runOnUiThread {
                        chapterList.addAll(0, it)
                        (binding.chapterBox.adapter as ReadTextItemAdapter).setData(chapterList)
                        (binding.chapterBox.adapter as ReadTextItemAdapter).notifyItemRangeInserted(
                            0,
                            pageSize
                        )
                    }
                }
            }
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        // 保存数据
        outState.putInt("bookId", bookId)
        outState.putInt("index", index)
        outState.putInt("directoryIndex", directoryIndex)
        outState.putInt("onePage", onePage)
        outState.putBoolean("isNight", isNight)
        outState.putBoolean("showHeaderNav", showHeaderNav)
        outState.putParcelableArrayList("directoryList", ArrayList(directoryList))
        outState.putParcelableArrayList("chapterList", ArrayList(chapterList))
        outState.putIntegerArrayList("pageList", ArrayList(pageList))
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        // 恢复数据
        bookId = savedInstanceState.getInt("bookId")
        index = savedInstanceState.getInt("index")
        directoryIndex = savedInstanceState.getInt("directoryIndex")
        onePage = savedInstanceState.getInt("onePage")
        isNight = savedInstanceState.getBoolean("isNight")
        showHeaderNav = savedInstanceState.getBoolean("showHeaderNav")
        directoryList = savedInstanceState.getParcelableArrayList("directoryList") ?: listOf()
        chapterList = savedInstanceState.getParcelableArrayList("chapterList") ?: mutableListOf()
        pageList = savedInstanceState.getIntegerArrayList("pageList") ?: mutableListOf()

        if (isNight) {
            binding.nightName.text = "日间"
            binding.nightIcon.setImageDrawable(resources.getDrawable(R.drawable.read_icon_bright))
        } else {
            binding.nightName.text = "夜间"
            binding.nightIcon.setImageDrawable(resources.getDrawable(R.drawable.read_icon_dark))
        }
        showHeaderNav = !showHeaderNav
        binding.chapterBox.performClick()

    }

    override fun onBackPressed() {
        super.onBackPressed()
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
    }

}